#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main() 
{
    int sock = 0;
    struct sockaddr_in saddr;
    
    //1. 创建套接字
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Socket creation error \n");
        return -1;
    }

    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(PORT);

    // 将IP地址从字符串转换为二进制形式
    if (inet_pton(AF_INET, "192.168.19.132", &saddr.sin_addr.s_addr) <= 0) 
    {
        printf("\nInvalid address/ Address not supported \n");
        return -1;
    }

    //2. 连接到服务器
    if (connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
        printf("\nConnection Failed \n");
        return -1;
    }

    //3. 发送消息到服务器
    int number = 0;
    char buffer[BUFFER_SIZE] = {0};
    while(1)
    {
        //发送信息
        sprintf(buffer, "hello word %d...\n", number++);
        send(sock, buffer, strlen(buffer)+1, 0);

        //接收信息
        memset(buffer, 0, sizeof(buffer));
        int len = recv(sock, buffer, sizeof(buffer), 0);
        if(len >0)
        {
            printf("server say: %s\n", buffer);
        }

        else  if(0 == len)
        {
            printf("服务端断开连接...\n");
            break;
        }

        else
        {
            perror("recv");
            break;
        }
        sleep(1);
        
    }
    
    // 关闭套接字
    close(sock);

    return 0;
}
    
